﻿using System;
using System.Web.Mvc;
using EnetaMvc.ApplicationServices;
using EnetaMvc.ApplicationServices.Dto;
using EnetaMvc.Web.Attributes;
using EnetaMvc.Web.Extensions;

namespace EnetaMvc.Web.Controllers
{
    public class ProfilesController : BaseController
    {
        private readonly INewsService _newsService;
        private readonly IUserService _userService;
        private readonly IContentService _contentService;

        public ProfilesController(INewsService newsService, IUserService userService, IContentService contentService)
        {
            _newsService = newsService;
            _userService = userService;
            _contentService = contentService;
        }
        
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Details(long id)
        {
            var profile = _userService.GetFullProfileById(id);
            if (profile == null)
            {
                return HttpNotFound("Your profile is not found");
            }

            return View(profile);
        }

        [HttpGet]
        [EnetaAuthorize(Roles = "User, Administrator")]
        public ActionResult Edit(long id = 0)
        {
            string token = User.Identity.Name;
            if (id == 0)
            {
                var user = _userService.GetUserByToken(token);
                id = user.Id;
            }

            var profile = _userService.GetFullProfileById(id);
            if (profile == null)
            {
                return HttpNotFound("Your profile is not found");
            }

            if (!User.IsInRole("Administrator"))
                if (token != profile.LiveIdToken)
                    return new HttpStatusCodeResult(401);

            return View(profile);
        }

        [HttpPost]
        //[EnetaAuthorize(Roles="User, Administrator")]
        public ActionResult Edit(FullProfileDto model)
        {
            if (Session["UserId"] == null)
            {
                return new HttpStatusCodeResult(401, "User ID is not found");
            }
            var userId = Session.GetUserId();
            if(userId != model.Id)
                if(!User.IsInRole("Administrator"))
                    return new HttpStatusCodeResult(401);

            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "VIGA!");
                return View(model);
            }

            if (Request.Form["MyRolesSelection"] != null)
            {
                var roleKeys = Request.Form["MyRolesSelection"].Split(",".ToCharArray());
                foreach (string roleKey in roleKeys)
                    model.MyRoles.Add(new MyRoleDto { Id = long.Parse(roleKey) });
            }

            _userService.SaveUser(model);
            
            if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
            { 
                var stream = Request.Files[0].InputStream;
                var bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);

                _userService.SaveProfileImage(userId, bytes);
            }

            ViewBag.SuccessMessage = Resources.EnetaMvc.ProfileDataSuccessfullySaved;
            return View(model);
        }

        [HttpPost]
        [EnetaAuthorize(Roles = "Administrator")]
        public ActionResult Lock(long id)
        {
            _userService.LockUser(id);

            return RedirectToAction("Details", new { id = id });
        }

        [HttpPost]
        [EnetaAuthorize(Roles="Administrator")]
        public ActionResult Unlock(long id)
        {
            _userService.UnlockUser(id);

            return RedirectToAction("Details", new { id = id });
        }

        [HttpGet]
        [EnetaAuthorize(Roles = "Administrator")]
        public ActionResult BlogCommandAction(long id, string commandName, string comment = "")
        {
            if (commandName == Resources.EnetaMvc.Edit)
            {
                return RedirectToAction("Edit", "Blogs", new { id = id });
            }

            var blog = _newsService.GetBlogById(id);
            var user = _userService.GetUserByToken(User.Identity.Name);

            if (!User.IsInRole("Administrator"))
                if (user.Id != blog.CreatedById)
                    return new HttpStatusCodeResult(403, "Cannot edit blog");

            if (commandName == Resources.EnetaMvc.Approve)
            {
                if (blog.PublishingStateId == 1)
                    return RedirectToAction("Details", new { id = id });

                blog.PublishingStateId = 1;
                blog.PublishingStateById = user.Id;
                blog.PublishingStateDate = DateTime.Now;
                blog.PublishingStateComment = string.Empty;

                _contentService.SaveBlogSlaitoringLog(blog.Id, blog.PublishingStateId, blog.PublishingStateById);
                _newsService.SaveBlog(blog);
            }
            if (commandName == Resources.EnetaMvc.Reject)
            {
                blog.PublishingStateId = 3;
                blog.PublishingStateById = user.Id;
                blog.PublishingStateDate = DateTime.Now;
                blog.PublishingStateComment = comment;

                _contentService.SaveBlogSlaitoringLog(blog.Id, blog.PublishingStateId, blog.PublishingStateById);
                _newsService.SaveBlog(blog);
            }

            return RedirectToAction("Details", new { id = blog.CreatedById });
        }
    }
}